<!doctype html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Marked in the browser</title>
</head>
<body>
<div style="position:fixed;padding-top:30px;width: 15%;min-width: 140px">
    <div id="leftTree">
</div>
</div>
<div id="content" style="width: 80%;float: right"></div>
<script src="lib/marked.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/marked/4.0.18/marked.min.js"></script>
<script src="lib/jquery-3.3.1.js" charset="utf-8"></script>
<script>
    //解析md文件
    $.ajax({
        url: './help.md',
        cache: false,
        type: 'GET',
        async: false,
        success: function (result) {
            document.getElementById('content').innerHTML = marked.parse(result);
        },
        error: function (result) {
            error_msg("服务器异常！")
        }
    });

    // 类似Java的hash生成方式，为一段文字生成一段基本不会重复的数字
    function _hashCode(txt) {
        var hash = 0;
        if (txt.length == 0) return hash;
        for (i = 0; i < txt.length; i++) {
            char = txt.charCodeAt(i);
            hash = ((hash<<5)-hash)+char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }

    document.addEventListener("DOMContentLoaded", function() {
        // 生成目录列表
        var outline = document.createElement("div");
        outline.className = "layui-panel";
        var ul = document.createElement("ul");
        ul.className = "layui-menu";
        outline.appendChild(ul);
        var divNode = document.getElementById("leftTree");
        //给div添加文本元素
        divNode.appendChild(outline);
        // 获取所有标题
        var headers = document.querySelectorAll('h1,h2,h3,h4,h5,h6');
        var lastPrefix;
        var lastTitle;
        for (var i = 0; i < headers.length; i++) {
            var header = headers[i];
            var hash = _hashCode(header.textContent);
            // MarkdownPad2无法为中文header正确生成id，这里生成一个
            header.setAttribute("id", header.tagName + hash);
            // 找出它是H几，为后面前置空格准备
            var prefix = parseInt(header.tagName.replace('H', ''), 10);
            var li = document.createElement("li");
            var spacing = 25 + prefix;
            li.style.cssText = "list-style: none;line-height:"+spacing+"px";
            var a = document.createElement("a");
            a.style.cssText = "text-decoration:none"
            // 为目录项设置链接
            a.setAttribute("href", "#" + header.tagName + hash)
            // 目录项文本前面放置对应的空格
            a.innerHTML = new Array(prefix * 4 - 4).join('&nbsp;') + header.textContent;
            var aDiv = document.createElement("div");
            aDiv.className = "layui-menu-body-title";
            aDiv.appendChild(a);
            li.appendChild(aDiv);
            ul.appendChild(li);
        }
    });
</script>

</body>
</html>